package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.entity.User;
import com.cy.store.service.IUserService;
import com.cy.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("users")
public class UserController extends BaseController{

    @Autowired
    private IUserService userService;   // 可能应该用实现类


    /**
     * 退出登录
     */
    @PostMapping("/quit")
    public JsonResult<Void> quit(HttpSession session){
        session.removeAttribute("uid");

        return new JsonResult<>(OK);
    }


    /**
     * 注册
     * @return json格式的user对象
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){

        userService.reg(user);

        return new JsonResult<>(OK);
    }


    /**
     * 测试
     */
    @RequestMapping("/Allt")
    public Boolean Allt(HttpServletRequest request){

        Object obj = request.getSession().getAttribute("uid");

        return obj != null;
    }









    /**
     * 登录
     * @param session 把返回的对象存放在session
     * @return json格式的user对象
     */
    @RequestMapping("/login")
    public JsonResult<User> login(String username, String password, String jzma, HttpSession session, HttpServletResponse response){



        User data = userService.login(username,password);

        // 功能：提取数据
        // 把返回对象的一些数据存放在session
        session.setAttribute("uid", data.getUid());
        session.setAttribute("username", data.getUsername());

        // 设置session的过期时间
        session.setMaxInactiveInterval(30*60);     // 秒

        System.err.println("登录者：" + getUsernameFromSession(session));
        System.err.println("登录者id：" + getuidFromSession(session));


        Cookie uname;
        Cookie upwd;

        if ("true".equals(jzma)){   // ?
            // 创建cookie
            uname = new Cookie("uname", username);
            upwd = new Cookie("upwd", password);

            // 设置保存时间
            uname.setMaxAge(10*24*60*60);
            upwd.setMaxAge(10*24*60*60);

            // 传回前端浏览器
        }else {
            // 创建cookie
            uname = new Cookie("uname", "name");
            upwd = new Cookie("upwd", "pww");

            // 设置保存时间
            uname.setMaxAge(0);
            upwd.setMaxAge(0);

            // 传回前端浏览器
        }

        response.addCookie(uname);
        response.addCookie(upwd);


        return new JsonResult<>(OK, data);
    }

    /**
     * 改密码
     */
    @RequestMapping("change_password")
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session){

        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        userService.changePassword(uid, username, oldPassword, newPassword);

        return new JsonResult<>(OK);
    }


    @RequestMapping("get_by_uid")
    public JsonResult<User> getByUid(HttpSession session){

        User data = userService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK, data);
    }

    @RequestMapping("change_info")
    public JsonResult<Void> changeInfo(User user, HttpSession session){

        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        userService.changeInfo(uid, username, user);
        return new JsonResult<>(OK);
    }

    // 传入文件的最大值
    final int AVATAR_MAX_SIZE = 10 * 1024 * 1024;

    // 传入文件的可选类型
    static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
        AVATAR_TYPE.add("image/webp");

    }

    @Value("${upload.uploadPath}")
    String uploadPath;


    /**
     * 上传文件
     * @param session uid 和 username
     * @param file 文件
     * @return 文件
     */
    @PostMapping("change_avatar")
    public JsonResult<String> changeAvatar(HttpSession session, @RequestParam("file") MultipartFile file) throws IOException {

        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }

        if(file.getSize() > AVATAR_MAX_SIZE){
            throw new FileSizeException("文件大小超出限制");
        }

        // 上传的文件类型
        String contentType = file.getContentType();

        // 判断文件类型是否支持
        // contains  如果包含则返回true
        if(!AVATAR_TYPE.contains(contentType)){
            throw new FileTypeException("无法识别此文件类型");
        }



        // 判断文件存放目录是否存在, 不存在就创建一个
        File dir = new File(uploadPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        // 获取文件名
        String originalFilename = file.getOriginalFilename();


        // 截取文件后缀
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);

        // 更换文件名
        String filename = UUID.randomUUID().toString().toUpperCase() + suffix;


        // 把上传的文件 写入 dest
        file.transferTo(new File(uploadPath, filename));



        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);

        // 文件路径
        String avatar = uploadPath + filename;
        System.err.println("文件保存路径" + uploadPath + filename);


        userService.changeAvatar(uid, avatar, username);
        return new JsonResult<>(OK, avatar);
    }

}
